package com.zrrd.yt.product.controller;

import com.zrrd.yt.common.result.Result;
import jodd.io.FileNameUtil;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/admin/product")
public class FileuploadController {

    //文件的服务器地址
    @Value("${fileServer.url}")
    private String fileUrl;

    @PostMapping("/fileUpload")
    public Result<String> fileUpload(MultipartFile file) throws MyException, IOException {
        //1.加载配置文件
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        //2.非空判断
        if(configFile != null){
            //3.初始化
            ClientGlobal.init(configFile);
            //4.创建上传的客户端对象
            TrackerClient client = new TrackerClient();
            //5.通过客户端对象获取连接对象(服务对象)
            TrackerServer connection = client.getConnection();
            //6.创建真正执行上传操作的任务对象
            StorageClient1 storageClient1 = new StorageClient1(connection,null);
            //7.执行上传
            String path = storageClient1.upload_appender_file1(file.getBytes(), FileNameUtil.getExtension(file.getOriginalFilename()), null);
            System.out.println("文件位置===>"+fileUrl + path);
            return Result.ok(fileUrl + path);
        }else{
            return Result.fail("文件上传初始化失败");
        }


    }
}
